﻿using CDSysLDManageProject.BYDTableAdapters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace CDSysLDManageProject
{
    class BYDMesDAL
    {


        //tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
        //tbl_FRDataTableAdapter fr = new tbl_FRDataTableAdapter();
        //T_CDResultDataTableAdapter cdresult = new T_CDResultDataTableAdapter();
        //rt_ProcessInfoTableAdapter processinfo = new rt_ProcessInfoTableAdapter();
        //T_TrayCellDataTableAdapter traycellinfo = new T_TrayCellDataTableAdapter();
        //rt_EndCodeInfoTableAdapter rtinfo = new rt_EndCodeInfoTableAdapter();
        //tb_RecipeInfoTableAdapter recipeinfo = new tb_RecipeInfoTableAdapter();
        int allowngcount = 3;
        /// <summary>
        /// 通过ECS架台位置获取托盘编号
        /// </summary>
        /// <param name="TrayLocation"></param>
        /// <returns></returns>
        public string GetTrayIdByLoc(string TrayLocation)
        {
            DataTable dttaskinfo = new DataTable();
            tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
            string TrayId = "";
            int allowngno = 3;
            int ngno = 0;
            try
            {
                
               
                dttaskinfo = task.GetTrayNoByToLocation(TrayLocation);
                if (dttaskinfo.Rows.Count <= 0)
                {
                    dttaskinfo = task.GetTrayNoByToLocation(TrayLocation);
                    ngno++;
                }

                
               
            }
            catch (Exception ex)
            {
                Log.SystemError.Add("获取架台的托盘号信息失败 " + ex.ToString());
                ngno++;
            }
            while (dttaskinfo.Rows.Count <= 0 && ngno<=allowngno)
            {
                try
                {
                    //tbl_LDTaskListTableAdapter task = new tbl_LDTaskListTableAdapter();
                   
                    if (dttaskinfo.Rows.Count <= 0)
                    {
                        dttaskinfo = task.GetTrayNoByToLocation(TrayLocation);
                        ngno++;
                    }
                  
                }
                catch (Exception ex )
                {

                    Log.SystemError.Add("获取架台的托盘号信息失败 "+ex.ToString());
                    ngno++;
                }
                
            }
            if (dttaskinfo.Rows.Count > 0)
            {
                TrayId = dttaskinfo.Rows[0]["trayno"].ToString();

                return TrayId;
            }
            else
            {
                Log.SystemError.Add("获取架台的托盘号信息失败,已超过允许查询次数");
                return "";
            }
            
        }
        /// <summary>
        /// 通过托盘号获取ECS的配方信息
        /// </summary>
        /// <param name="TrayId">托盘号</param>
        /// <returns></returns>
        public string GetRecipeIDByTrayId(string TrayId)
        {
            DataTable dttraycellinfo=new DataTable();
            DataTable dtprocessinfo=new DataTable();
            T_TrayCellDataTableAdapter traycellinfo = new T_TrayCellDataTableAdapter();
            rt_ProcessInfoTableAdapter processinfo = new rt_ProcessInfoTableAdapter();
            int allowngcount=3;
            int ngcount=0;
            int ngcount1=0;
            DateTime starttime;
            DateTime endtime;
            starttime = DateTime.Now;
            
            try 
	        {	       
		        dttraycellinfo=traycellinfo.GetCellNoByTrayNo(TrayId);
                ngcount++;
	        }
	        catch (Exception ex)
	        {

                Log.SystemError.Add("根据托盘号获取电池信息失败!" + ex.ToString());
                ngcount++;
                endtime = DateTime.Now;
                //查询时间超过15s就算超时。
                TimeSpan ts = endtime.Subtract(starttime);
                float secs = float.Parse(ts.TotalSeconds.ToString());
                if (secs > 15)
                {
                    ngcount = 6;
                }
	        }
            


            try
            {
                while (dttraycellinfo.Rows.Count <= 0 && ngcount < allowngcount)
                {
                    dttraycellinfo = traycellinfo.GetCellNoByTrayNo(TrayId);
                    ngcount++;
                }
            }
            catch (Exception ex)
            {
                Log.SystemError.Add("根据托盘号获取电池信息失败!" + ex.ToString());
                ngcount++;
            }


            if (dttraycellinfo.Rows.Count > 0)
            {
                //判断41<=电池日期<=71
                //int date = int.Parse(dttraycellinfo.Rows[0]["CELL_NO"].ToString().Substring(3,2));
                //if (date >= 41 && date <= 71)
                //{
                //    return "";
                //}

                //获取SEC工艺号
                int CD2_TEST_NO = int.Parse(dttraycellinfo.Rows[0]["CD2_TEST_NO"].ToString());
                ////判断电池是否是实验电池
                //if (CD2_TEST_NO == 85 && CD2_TEST_NO == 40)
                //{
                //    return "";
                //}



                //try 
                //{	        
                //    dtprocessinfo=processinfo.GetProcessInfo();
                //    ngcount1++;
                //}
                //catch (Exception ex )
                //{

                //    Log.SystemError.Add("获取全部工艺信息失败！"+ex.ToString());
                //    ngcount1++;
                //}


                //try
                //{
                //    while (dtprocessinfo.Rows.Count <= 0 && ngcount1 < allowngcount)
                //    {
                //        dtprocessinfo = processinfo.GetProcessInfo();
                //        ngcount1++;
                //    }
                //}

                //catch (Exception ex)
                //{
                //    Log.SystemError.Add("获取全部工艺信息失败！" + ex.ToString());
                //    ngcount1++;
                //}


                //if (dtprocessinfo.Rows.Count>0 )
                //{
                //    DataRow[] dr = dtprocessinfo.Select("secprocessno=" + CD2_TEST_NO );
                //    if (dr.Length > 0)
                //    {
                //        string kpprocessno = dr[0]["kpprocessno"].ToString();
                //        return kpprocessno;
                //    }
                //    else
                //    {

                if (CD2_TEST_NO == 19)
                {
                    string traytype = TrayId.Substring(TrayId.Length - 3, 3);
                    if (traytype == "C15" || traytype == "C12")
                    {
                        traytype = "C15";
                        string kpprocessno = GetRecipeID(traytype);
                        return kpprocessno;

                    }
                    else if (traytype == "C19")
                    {
                        string kpprocessno = GetRecipeID(traytype);
                        return kpprocessno;
                    }

                }
                else
                {
                    try
                    {
                        dtprocessinfo = processinfo.GetProcessInfo();
                        ngcount1++;
                    }
                    catch (Exception ex)
                    {

                        Log.SystemError.Add("获取全部工艺信息失败！" + ex.ToString());
                        ngcount1++;
                    }


                    //try
                    //{
                    //    while (dtprocessinfo.Rows.Count <= 0 && ngcount1 < allowngcount)
                    //    {
                    //        dtprocessinfo = processinfo.GetProcessInfo();
                    //        ngcount1++;
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    Log.SystemError.Add("获取全部工艺信息失败！" + ex.ToString());
                    //    ngcount1++;
                    //}


                    if (dtprocessinfo.Rows.Count > 0)
                    {
                        DataRow[] dr = dtprocessinfo.Select("secprocessno=" + CD2_TEST_NO);
                        if (dr.Length > 0)
                        {
                            string kpprocessno = dr[0]["kpprocessno"].ToString();
                            return kpprocessno;
                        }
                        else
                        {
                            return "";
                        }
                    }
                    else
                    {
                        return "";
                    }
                }
            }
            else
            {
                return "";
            }

            return "";

            
        }
        /// <summary>
        /// 通过托盘类型获取配方号
        /// </summary>
        /// <param name="TrayId">托盘类型</param>
        /// <returns></returns>
        public string GetRecipeID(string traytype)
        {
            DataTable dtrecipeinfo = new DataTable();
            int allowngno = 3;
            int ngno = 1;
            try
            {
                tb_RecipeInfoTableAdapter recipeinfo = new tb_RecipeInfoTableAdapter();
                dtrecipeinfo = recipeinfo.GetRecipeInfoByRecipeid(traytype);
                ngno++;
            }
            catch (Exception ex)
            {
                Log.SystemError.Add("获取" + traytype + "类型的配方号失败" + ex.ToString());
                ngno++;
            }

            while (dtrecipeinfo.Rows.Count <= 0 && ngno <= allowngno)
            {
                try 
	            {
                    tb_RecipeInfoTableAdapter recipeinfo = new tb_RecipeInfoTableAdapter();
                    dtrecipeinfo = recipeinfo.GetRecipeInfoByRecipeid(traytype);
                    ngno++;
	            }
	            catch (Exception ex)
	            {
		            Log.SystemError.Add("获取"+traytype+"类型的配方号失败"+ex.ToString());
                    ngno++;
	            }
                
                
            }

            if (dtrecipeinfo.Rows.Count > 0)
            {
                return dtrecipeinfo.Rows[0]["recipeid"].ToString();
            }
            else
            {
                Log.SystemError.Add("获取配方号信息失败,已超过允许查询次数");
                return "";
            }

         
        }


        /// <summary>
        /// 通过托盘号获取当前托盘号上的电池信息
        /// </summary>
        /// <param name="TrayId">托盘号</param>
        /// <returns></returns>
        public string GetCellInfoByTrayId(string TrayId)
        {
            string cellno = "";
            DataTable dtcellno = new DataTable();
            T_TrayCellDataTableAdapter traycell = new T_TrayCellDataTableAdapter();
            int allowngno = 2;
            int ngno = 0;
            DateTime starttime ;
            DateTime endtime;
            starttime = DateTime.Now;
            try
            {
                 
                dtcellno = traycell.GetCellNoByTrayNo(TrayId);
                ngno++;
            }
            catch (Exception ex)
            {
                Log.SystemError.Add("根据托盘号获取电池编号失败，托盘号是"+TrayId + ex.ToString());
                ngno++;
            }
                 endtime = DateTime.Now;
                //查询时间超过15s就算超时。
                 TimeSpan ts = endtime.Subtract(starttime);
                 float secs = float.Parse(ts.TotalSeconds.ToString());
                 if (secs > 15)
                 {
                     ngno = 6;
                 }

            while (dtcellno.Rows.Count<=0&&ngno <= allowngno)
            {
                try
                {
                    
                    dtcellno = traycell.GetCellNoByTrayNo(TrayId);
                    ngno++;
                }
                catch (Exception ex)
                {

                    Log.SystemError.Add("根据托盘号获取电池编号失败，托盘号是" + TrayId + ex.ToString());
                    ngno++;
                }
                
            }

            if (dtcellno.Rows.Count > 0)
            {
                for (int i = 0; i < dtcellno.Rows.Count; i++)
                {
                    cellno = cellno + dtcellno.Rows[i]["CELL_NO"].ToString().PadRight(20, ' ');
                }
                return cellno;
            }
            else
            {
                Log.SystemError.Add("根据托盘获取电池信息失败,已超过允许查询次数");
                return "";
            }   
        }

        /// <summary>
        /// 更新架台状态
        /// </summary>
        /// <param name="stagestatus">架台状态Mod(无架台顺序号)</param>
        /// <returns></returns>
        public bool UpdateStageStatus(StageStatusMod stagestatus)
        {
            bool flag = false;
            tbl_stageinfoTableAdapter stageinfo = new tbl_stageinfoTableAdapter();
            try
            {
                stageinfo.UpdateStageStatus(stagestatus.Workmode.ToString(), stagestatus.Currentst.ToString(), stagestatus.Chargest.ToString(), stagestatus.Channelst.ToString(), stagestatus.Emgst.ToString(),stagestatus.Stagelocation);
                flag = true;
            }
            catch (Exception)
            {
                //Log.WriteLog(LogFile.SystemError,"更新"+stagestatus.Stagelocation+"架台信息失败");
                Log.SystemError.Add("更新" + stagestatus.Stagelocation + "架台信息失败");
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 获取指定架台位置堆垛机叉子状态
        /// </summary>
        /// <param name="stageLoc">架台位置编号</param>
        /// <returns></returns>
        public string GetLDForkStByStageLoc(string stageLoc)
        {
            return "1";//0 : Fork MOVE, 1: Fork Home
        }

        /// <summary>
        /// 保存充放电结果
        /// </summary>
        /// <param name="cdResult"></param>
        /// <returns></returns>
        public bool InsertStepResult(CDStepResult cdResult)
        {
            tbl_FRDataTableAdapter fr = new tbl_FRDataTableAdapter();
            T_CDResultDataTableAdapter cdresult = new T_CDResultDataTableAdapter();
            //int dtcount = int.Parse(fr.GetCountByTrayNoStepNoTime(cdResult.CellID, cdResult.TrayID, cdResult.StepNumber, cdResult.EndTime).ToString());
            DataTable dtCellData = fr.GetCellDataByTrayCellNoEndTime(cdResult.CellID, cdResult.TrayID, cdResult.EndTime);
            DataRow[] dr = dtCellData.Select("stepno=" + cdResult.StepNumber);

            if (dr.Length > 0)
            {

            }
            else
            {
                fr.InsertFrData(cdResult.StageLoc, cdResult.TrayID, cdResult.StartTime, cdResult.EndTime, cdResult.CellID, cdResult.T1Voltage, cdResult.T2Voltage, cdResult.T3Voltage, cdResult.dTVoltage, cdResult.StepCount, cdResult.StepNumber, cdResult.Voltage, cdResult.Current, cdResult.Capacity, cdResult.CVCapa, cdResult.CVTime, cdResult.Time, cdResult.CellStatus, int.Parse(cdResult.CellCH.ToString()),cdResult.RecipeID);
                //将结果数据存储到BYD T_CDResultData表
                //
                int cd2Count = int.Parse(cdresult.GetCellCountNo(cdResult.CellID.ToString(), 2, int.Parse(cdResult.StepNumber)).ToString());
                if (cd2Count > 0)
                {
                    cdresult.DeleteCellCDData(cdResult.CellID.ToString(), 2, int.Parse(cdResult.StepNumber));
                    InsertDataIntoT_CDResult(cdResult.TrayID, cdResult.EndTime, int.Parse(cdResult.StepCount), cdResult.StageLoc);
                }
                else
                {
                    InsertDataIntoT_CDResult(cdResult.TrayID, cdResult.EndTime, int.Parse(cdResult.StepCount), cdResult.StageLoc);
                }
                //将结果数据存储到BYD T_MESResultMessage表
                InsertDataIntoMESResultTable(cdResult.TrayID, cdResult.EndTime, int.Parse(cdResult.StepCount), cdResult.StageLoc);
            
            }
            
            return true;
        }
        //将结果数据存储到BYD T_CDResultData表
        public void InsertDataIntoT_CDResult(string TrayNo,DateTime EndTime,int StepCount,string StageLoc)
        {
            //这里将数据同步到BYD T_CDResultData表
            T_CDResultDataTableAdapter cdresult = new T_CDResultDataTableAdapter();
            tbl_FRDataTableAdapter fr = new tbl_FRDataTableAdapter();
            int traycount = int.Parse(fr.GetTrayDataCount(TrayNo, EndTime).ToString());
            if (traycount >= StepCount * 16)
            {
                DataTable dtCellData = fr.GetCellDataByTrayEndTime(TrayNo, EndTime);

                for (int i = 1; i <= StepCount; i++)
                {
                    string STEP_MODE = "";
                    string STAGE = "3-" + StageLoc.Substring(4, 2) +"-"+ StageLoc.Substring(StageLoc.Length - 1, 1);
                    Double START_V;
                
                   
                    if (i == 1)
                    {
                        DataRow[] dr = dtCellData.Select("stepno=1");
                        for (int j = 0; j < dr.Length; j++)
                        {

                            if (i % 2 == 0)
                            {
                                STEP_MODE = "休止";
                            }
                            else
                            {
                                STEP_MODE = "充电";
                            }
                            string END_CODE1 = dr[j]["cellstatus"].ToString();
                            cdresult.InsertDataIntoCDResultData(dr[j]["cellno"].ToString(), 2, i, STEP_MODE, 0, STAGE, DateTime.Parse(dr[j]["starttime"].ToString()), double.Parse(dr[j]["voltage"].ToString()) / 1000, 28, 0, 0, DateTime.Parse(dr[j]["endtime"].ToString()), double.Parse(dr[j]["voltage"].ToString()) / 1000, double.Parse(dr[j]["current1"].ToString()), double.Parse(dr[j]["capacity"].ToString()), double.Parse(dr[j]["capacity"].ToString()) * double.Parse(dr[j]["current1"].ToString()), 32, int.Parse(END_CODE1), 0);
                            
                            
                        }

                    }
                    else
                    {
                        DataRow[] dr = dtCellData.Select("stepno='" + i + "'");
                        for (int j = 0; j < dr.Length; j++)
                        {
                            DataRow[] dr2 = dtCellData.Select("cellno='" + dr[j]["cellno"].ToString() + "' and stepno='" + (i-1) + "'");
                            if (dr2.Length > 0)
                            {
                                START_V = Double.Parse(dr2[0]["voltage"].ToString());
                                START_V = START_V / 1000.0;
                                if (i % 2 == 0)
                                {
                                    STEP_MODE = "休止";
                                }
                                else
                                {
                                    STEP_MODE = "充电";
                                }
                                string END_CODE1 = dr[j]["cellstatus"].ToString();
                                cdresult.InsertDataIntoCDResultData(dr[j]["cellno"].ToString(), 2, i, STEP_MODE, 0, STAGE, DateTime.Parse(dr[j]["starttime"].ToString()), START_V, 28, 0, 0, DateTime.Parse(dr[j]["endtime"].ToString()), double.Parse(dr[j]["voltage"].ToString()) / 1000, double.Parse(dr[j]["current1"].ToString()), double.Parse(dr[j]["capacity"].ToString()), double.Parse(dr[j]["capacity"].ToString()) * double.Parse(dr[j]["current1"].ToString()), 32, int.Parse(END_CODE1), 0);
                               
                            
                               
                                

                            }
                            else
                            {
                                Log.SystemError.Add("将3线分容数据存储到T_CDResult表时查找当前工步的上一步的电压出错!电池条码是" + dr[j]["cellno"].ToString());
                            }

                        }
                    }
                }
            }
        }

        //将数据持久化到177服务器的T_MESResultMessageTable。
        public void InsertDataIntoMESResultTable(string TrayNo, DateTime EndTime, int StepCount, string StageLoc)
        {
            T_MESResultMessageTableTableAdapter mesresult = new T_MESResultMessageTableTableAdapter();
            tbl_FRDataTableAdapter fr = new tbl_FRDataTableAdapter();
            rt_ProcessInfoTableAdapter processinfo = new rt_ProcessInfoTableAdapter();
            double StartV;
            double EndV = 0;
            int ngcode = 0;
            DateTime startdt;
            DateTime enddt;
            string cellno = "";
            int processmode = 1;
            int celltypeno;
            int testno;
            double chargecapcity = 0;
            double dischargecapcity = 0;
            string recipeid = "";
            string trayno = "";
            DataTable dt2 =new DataTable();
            int ngcount = 0;
            DateTime starttime;
            DateTime endtime;
            starttime = DateTime.Now;

            try
            {
                dt2 = fr.GetCellDataByTrayEndTime(TrayNo, EndTime);
                ngcount++;
            }
            catch (Exception ex)
            {
                Log.SystemError.Add("根据托盘号和结束时间获取电池分容信息失败!" + ex.ToString());
                ngcount++;
                endtime = DateTime.Now;
                //查询时间超过15s就算超时。
                TimeSpan ts = endtime.Subtract(starttime);
                float secs = float.Parse(ts.TotalSeconds.ToString());
                if (secs > 15)
                {
                    ngcount = 6;
                }
            }


           


            try
            {
                while (dt2.Rows.Count <= 0 && ngcount < allowngcount)
                {
                    dt2 = fr.GetCellDataByTrayEndTime(TrayNo, EndTime);
                    ngcount++;
                }
            }
            catch (Exception ex)
            {
                Log.SystemError.Add("根据托盘号和结束时间获取电池分容信息失败 !" + ex.ToString());
                ngcount++;
            }


            
            trayno = dt2.Rows[0]["trayno"].ToString();
            recipeid = dt2.Rows[0]["recipeid"].ToString();
            //获取特殊工艺信息
            DataTable dtprocessinfo = processinfo.GetProcessInfo() ;
            DataRow[] dr0 = dtprocessinfo.Select("kpprocessno='" + recipeid+"'");
            if (dr0.Length > 0)
            {
                testno = int.Parse(dr0[0]["secprocessno"].ToString());
            }
            else
            {
                testno = 20;
            }
            for (int i = 1; i <= 16; i++)
            {
                //第1步的开始电压
                DataRow[] dr = dt2.Select("chno='" + i.ToString().PadLeft(2, '0') + "' and stepno='1'");
                if (dr.Length > 0)
                {

                    StartV = double.Parse(dr[0]["voltage"].ToString());
                    StartV = StartV / 1000.0;
                    TrayNo = dr[0]["trayno"].ToString();
                    cellno = dr[0]["cellno"].ToString();
                    startdt = DateTime.Parse(dr[0]["starttime"].ToString());
                    enddt = DateTime.Parse(dr[0]["endtime"].ToString());
                    if (TrayNo.Contains("C15"))
                    {
                        celltypeno = 3;
                    }
                    else if (TrayNo.Contains("C12"))
                    {
                        celltypeno = 1;
                    }
                    else
                    {
                        celltypeno = 2;
                    }
                    //第4步的放电电容量,正常和返修一样
                    DataRow[] dr2 = dt2.Select("chno='" + i.ToString().PadLeft(2, '0') + "' and stepno='4'");
                    if (dr2.Length > 0)
                    {
                        dischargecapcity = double.Parse(dr2[0]["capacity"].ToString());
                    }
                    //判断是否是返工，返工的工艺是8步,如果是返工的话结束电压是第8步的，如果是正常的话结束电压是第6步的。
                    //第8步的充电容量
                    if (dt2.Rows.Count>96)
                    {
                        DataRow[] dr3 = dt2.Select("chno='" + i.ToString().PadLeft(2, '0') + "' and stepno='8'");
                        if (dr3.Length > 0)
                        {
                            chargecapcity = double.Parse(dr3[0]["capacity"].ToString());
                            EndV = double.Parse(dr3[0]["voltage"].ToString());
                            EndV = EndV / 1000.0;
                            ngcode = int.Parse(dr3[0]["cellstatus"].ToString());
                        }
                    }
                    else
                    {
                        //正常充放电容量及正常结束电压。
                        chargecapcity = 0;
                        DataRow[] dr1 = dt2.Select("chno='" + i.ToString().PadLeft(2, '0') + "' and stepno='6'");
                        if (dr1.Length > 0)
                        {
                            EndV = double.Parse(dr1[0]["voltage"].ToString());
                            EndV = EndV / 1000.0;
                            ngcode = int.Parse(dr1[0]["cellstatus"].ToString());
                        }
                    }

                    try
                    {
                        mesresult.InsertMESResultData(TrayNo, DateTime.Now, cellno, i, "K", "3", null, startdt, enddt, processmode, celltypeno, testno, StartV, EndV, ngcode, chargecapcity, dischargecapcity, 0, null, 0, null, null, null, null, 4);
                    }
                    catch (Exception ex)
                    {
                        Log.SystemError.Add("将分容结果数据插入MES中间表失败 !" + ex.ToString());
                        
                    }
                    


                }


            }
        }

    }
}
